package com.example.mobile2021606128wje0615;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class MyDataAdapter {
    private MySQLiteOpenHelper openHelper;
    private SQLiteDatabase database;
    public void openDB(Context context){
        openHelper =new MySQLiteOpenHelper( context,"student.db",null,1 );
        try {
            database=openHelper.getWritableDatabase();
        }catch (Exception e){
            database=openHelper.getReadableDatabase();
        }
    }
    public void closeDB() {
        if (database != null) {
            database.close();
            database = null;
        }
        if (openHelper != null) {
            openHelper.close();
            openHelper = null;
        }
    }
    public List<StudentScore> QueryAll(Context context) {
        List<StudentScore> studentScoreArrayList = new ArrayList<>();
        openDB( context );
        Cursor cursor = database.query( "users", null, null, null,
                null, null, null);
        if (cursor.moveToFirst()) {
            do {
                int id = cursor.getInt( 0 );
                String name = cursor.getString( 1 );
                int age = cursor.getInt( 2 );
                float score = cursor.getFloat( 3 );
                studentScoreArrayList.add( new StudentScore( id, name, age, score ) );
            } while (cursor.moveToNext());
        }
        cursor.close();
        closeDB();
        return studentScoreArrayList;

    }
}
